package com.qf.petmall.starter.login.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.qf.petmall.starter.ex.QFException;
import com.qf.petmall.starter.login.CreateTooken;
import com.qf.petmall.starter.login.duanxin.CheckSumBuilder;
import com.qf.petmall.starter.login.entity.Users;
import com.qf.petmall.starter.login.entity.Uservo;
import com.qf.petmall.starter.login.service.IUsersService;
import com.qf.petmall.starter.utils.CommonConstants;
import com.qf.petmall.starter.utils.R;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 用户  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-12-05
 */

@CrossOrigin
@RestController
@RequestMapping("/users")
public class UsersController {

    private static final String
            SERVER_URL="https://api.netease.im/sms/sendcode.action";
    private static final String
            APP_KEY="63b8f826ff30214c8cd1b9d7f2854a40";
    //网易云信分配的密钥，请替换你在管理后台应用下申请的appSecret
    private static final String APP_SECRET="61e7fb70c56d";
    //随机数
    private static final String NONCE= UUID.randomUUID().toString().substring(0,6);
    //短信模板ID
//    private static final String TEMPLATEID="3057527";
    //手机号
 /*   private static final String MOBILE="18841773052";*/
    //验证码长度，范围4～10，默认为4
    private static final String CODELEN="5";

    private static final Map<String,String> map1=new HashMap<>();

    @Autowired
    IUsersService usersService;


    /**
     * 第二次注册的时候验证两次密码是否一样，如果一样，直接注册在数据库中
     * @param user
     * @return
     */
    @PostMapping("/logon1")
    public R regist(@RequestBody Users user){

        boolean regist = usersService.regist(user);

        if(regist){
            return R.ok().put("code","200");
        }else {
            return R.ok().put("code","400");
        }


    }

    /**
     * 第一次注册的时候需要验证username是否存在
     * @param user
     * @return
     */
    @PostMapping("/logon")
    public R logon(@RequestBody Users user){
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Users> username = usersQueryWrapper.eq("username", user.getUsername());
        Users one = usersService.getOne(username);
        if(one!=null){
            return R.ok().put("code","400");
        }else {
            return R.ok().put("code","200");
        }
    }

    @PostMapping("/login")
    public R login(@RequestBody Users users) throws JsonProcessingException {
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(new UsernamePasswordToken(users.getUsername(),users.getPassword()));
        } catch (AuthenticationException e) {
            throw new QFException("用户名或者密码错误");
        }
        final Users user = (Users) subject.getPrincipal();

        // 生成服务器端的token，用于后续的请求验证用户的身份
        String token = CreateTooken.createToken(user);

        //2. 返回json
        return R.ok().put("code", "200").put("user",user).put("token",token);

    }


    @GetMapping("/getnum")
    public R getphone( String username) throws IOException {

        this.getnum(username);
        return R.ok();
    }

    @PostMapping("/login1")
    public R login1(@RequestBody Uservo uservo) throws JsonProcessingException {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Users> username1 = usersQueryWrapper.eq("username", uservo.getUsername());
        Users one = usersService.getOne(username1);
  /*      if(number.equals(map.get(username))){
            String token = createToken(one);
            return R.ok(token).put("code", 200).put("user",one);
        }
        else {
            return R.ok().put("code",400);
        }*/
        if(uservo.getNumber().equals(map1.get(uservo.getUsername()))){
            String token = CreateTooken.createToken(one);
            return R.ok().put("code", "200").put("user",one).put("token",token);
        }
        else {
            return R.ok().put("code",400);
        }
    }




    public void getnum(String username) throws IOException {
        //网易云信分配的账号，请替换你在管理后台应用下申请的Appkey

            // 创建用于发送http请求的核心对象 ，类似 restTemplate
            DefaultHttpClient httpClient = new DefaultHttpClient();

            // 发送Http post请求创建 HttpPost对象
            HttpPost httpPost = new HttpPost(SERVER_URL);

            String curTime = String.valueOf((new Date()).getTime() / 1000L);
            /*
             * 参考计算CheckSum的java代码，在上述文档的参数列表中，有CheckSum的计算文档示例
             */
            String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);

            // 设置请求的header
            httpPost.addHeader("AppKey", APP_KEY);
            httpPost.addHeader("Nonce", NONCE);
            httpPost.addHeader("CurTime", curTime);
            httpPost.addHeader("CheckSum", checkSum);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            // 设置请求的的参数，requestBody参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            /*
             * 1.如果是模板短信，请注意参数mobile是有s的，详细参数配置请参考“发送模板短信文档”
             * 2.参数格式是jsonArray的格式，例如 "['13888888888','13666666666']"
             * 3.params是根据你模板里面有几个参数，那里面的参数也是jsonArray格式
             */
//        nvps.add(new BasicNameValuePair("templateid", TEMPLATEID));
            nvps.add(new BasicNameValuePair("mobile", username));
//        nvps.add(new BasicNameValuePair("codeLen", CODELEN));
            int num = (int) ((Math.random() * 9 + 1) * 100000);
            map1.put(username,num+"");
            nvps.add(new BasicNameValuePair("authCode",num+"" ));


            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
            /*
             * 1.打印执行结果，打印结果一般会200、315、403、404、413、414、500
             * 2.具体的code有问题的可以参考官网的Code状态表
             */
            final StatusLine statusLine = response.getStatusLine();
            System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));

        }


    @RequestMapping("/getmapping/{token}")
    public R gettoken(@PathVariable("token")String token){

        String username=(String)Jwts.parser().setSigningKey(CommonConstants.JWT_SECRET_KEY).parseClaimsJws(token).getBody().get("sub");
        LambdaQueryWrapper<Users> usersLambdaQueryWrapper = new LambdaQueryWrapper<>();

        usersLambdaQueryWrapper.eq(Users::getUsername,username);

        Users one = usersService.getOne(usersLambdaQueryWrapper);

        return R.ok().put("200",one);

    }



    }

